<template>
  <div id="socket-box" :class="{ active: isShowWindow }">
    <div>
      <stu_examDialog
        ref="stu_examDialog"
        v-show="isShowAi"
        @closeFn="handleCloseAI"
        :examName="agentName"
        :agentId="agentId"
        :classId="classId"
      />
      <!-- <div v-show="isShowAi" class="close-btn" @click="handleCloseAI">
        <el-icon>
          <CircleCloseFilled />
        </el-icon>
      </div> -->
    </div>
    <el-dialog
      v-model="dialogVisible"
      :close-on-click-modal="false"
      width="550"
      :before-close="handleClose"
      :show-close="true"
    >
      <div class="my-dialog">
        <div class="my-dialog-content">
          <div class="dialog-img">
            <img src="@/assets/img/lu-large.png" alt="" />
          </div>
          <div class="dialog-txt">
            {{ teacherName }}老师为你准备了<span class="bold">{{
              agentName
            }}</span
            >测验<br />点击立即挑战！
          </div>
        </div>
        <div class="dialog-footer">
          <el-button color="#155EEF" @click="handleDialogClick">
            立即挑战
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
  
  <script>
import Agent from "@/components/Agent.vue";
import stu_examDialog from "@/components/stu_examDialog.vue";

export default {
  components: {
    Agent,
    stu_examDialog,
  },
  data() {
    return {
      roles: "", // 用户角色
      isShowWindow: false, // 是否显示窗口
      dialogVisible: true, // 修改为false，只在接收到消息时才显示
      isShowAi: false, // 是否显示 AI 组件
      messages: [], // 存储接收到的消息
      agentName: "",
      agentId: null,
      classId: null,
      teacherName: "",
      agentName: "",
    };
  },
  created() {
    this.roles = JSON.parse(localStorage.getItem("userInfo")).roles[0];
  },
  mounted() {
    // console.log("socket对象", this.$websocket);
    this.initializeWebSocket();
  },
  beforeDestroy() {
    this.cleanupWebSocket();
  },
  methods: {
    /**
     * 初始化 WebSocket
     */
    initializeWebSocket() {
      console.log("socket对象", this.$websocket);
      if (this.$websocket && this.$websocket.state.manager) {
        this.setupWebSocketListeners();
        return;
      }
    },

    /**
     * 设置 WebSocket 监听器
     */
    setupWebSocketListeners() {
      this.$websocket.state.manager.on("message", (data) => {
        console.log("组件监听到消息", data);
        if (this.roles === "student") {
          //字符串data转对象
          const obj = JSON.parse(data);
          this.agentName = obj.data[0].agentName;
          this.classId = Number(obj.data[0].classId);
          this.isShowWindow = true;
          this.agentId = Number(obj.data[0].id);
          this.teacherName = obj.data[0].teacherName;

          // 使用nextTick确保DOM更新后再显示弹窗
          this.$nextTick(() => {
            this.dialogVisible = true;
          });
        }
      });

      this.$websocket.state.manager.on("error", (error) => {
        console.error("WebSocket error in component:", error);
      });
    },

    /**
     * 清理 WebSocket 实例和监听器
     */
    cleanupWebSocket() {
      if (this.$websocket) {
        this.$websocket.state.manager.off("message");
        this.$websocket.state.manager.off("error");
        this.$websocket.state.manager.close();
      }
    },

    /**
     * 发送消息到 WebSocket
     */
    sendMessage() {
      if (!this.$websocket || !this.$websocket.state.manager) {
        console.warn("WebSocket is not available for this user.");
        return;
      }

      const message = "Hello, WebSocket!";
      this.$websocket.state.manager.send(message);
    },

    handleClose() {
      this.$confirm("您确定要关闭此窗口吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          // 用户点击“确定”后执行关闭逻辑
          this.dialogVisible = false;
          this.isShowWindow = false;
        })
        .catch(() => {
          // 用户点击“取消”时不执行任何操作
          this.$message({
            type: "info",
            message: "操作已取消",
          });
        });
    },
    handleCloseAI() {
      this.$confirm("您确定要关闭此窗口吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.isShowWindow = false;
          this.$refs.stu_examDialog.closeDialog();
        })
        .catch(() => {
          // 用户点击“取消”时不执行任何操作
          this.$message({
            type: "info",
            message: "操作已取消",
          });
        });
    },
    handleDialogClick() {
      this.dialogVisible = false;
      this.isShowAi = true;
      this.$nextTick(() => {
        this.$refs.stu_examDialog.openFn();
      });
    },
  },
};
</script>
  
  <style lang="scss" scoped>
#socket-box {
  position: fixed;
  top: -999999px;
  left: -999999px;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  z-index: -1;
  display: flex;
  justify-content: center;
  align-items: center;

  > div {
    width: 80%;
    height: 80%;
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .agent {
    width: 100%;
    height: 100%;
  }

  .close-btn {
    position: absolute;
    top: -30px;
    right: 0px;
    cursor: pointer;
    color: #fff;
    font-size: 20px;
    font-weight: bold;

    &:hover {
      opacity: 0.8;
    }
  }

  &.active {
    top: 0;
    left: 0;
    z-index: 2002;
  }
  .my-dialog {
    .my-dialog-content {
      margin-bottom: 34px;
      .dialog-img {
        width: 69px;
        height: 69px;
        margin: 40px auto 28px;
        img {
          width: 100%;
          height: 100%;
        }
      }
      .dialog-txt {
        text-align: center;
        font-size: 18px;
        color: #34323d;
        line-height: 30px;
        .bold {
          font-weight: bold;
        }
      }
    }
    .dialog-footer {
      display: flex;
      justify-content: center;
      margin-bottom: 58px;
    }
  }
}

// 确保弹窗层级足够高
:deep(.el-dialog) {
  z-index: 2003 !important;
}

// 确保确认弹窗层级更高
:deep(.el-message-box__wrapper) {
  z-index: 2004 !important;
}
</style>